package com.sqfw.project.knowledge.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.sqfw.common.enums.knowledge.KlContentOpeTypeEnum;
import com.sqfw.common.enums.knowledge.KlContentSearchTypeEnum;
import com.sqfw.common.enums.knowledge.KlContentStatusEnum;
import com.sqfw.common.enums.knowledge.KlContentStatusTypeEnum;
import com.sqfw.common.utils.DateUtils;
import com.sqfw.common.utils.PageUtils;
import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.framework.security.LoginUser;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.project.knowledge.domain.KlContentFileInfo;
import com.sqfw.project.knowledge.domain.KlContentInfo;
import com.sqfw.project.knowledge.domain.KlContentScoreLog;
import com.sqfw.project.knowledge.domain.KlContentStatusLog;
import com.sqfw.project.knowledge.domain.KlContentVerifyLog;
import com.sqfw.project.knowledge.domain.KlOperationsLog;
import com.sqfw.project.knowledge.domain.KnowledgeSort;
import com.sqfw.project.knowledge.domain.cms.CmsKnowledge;
import com.sqfw.project.knowledge.domain.query.KlContentInfoQuery;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoCountVo;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoExcel;
import com.sqfw.project.knowledge.domain.vo.KnowledgeSortVo;
import com.sqfw.project.knowledge.mapper.*;
import com.sqfw.project.knowledge.service.KlContentService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 知识模块的 impl
 *
 * @author tangxt
 * @date 2023-06-09
 * */
@Slf4j
@Service
public class KlContentServiceImpl implements KlContentService {

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private KnowledgeSortMapper knowledgeSortMapper;

    @Autowired
    public KlContentInfoMapper klContentInfoMapper;

    @Autowired
    private KlOperationsLogMapper klOperationsLogMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private KlContentStatusLogMapper klContentStatusLogMapper;

    @Autowired
    private KlContentScoreLogMapper klContentScoreLogMapper;

    @Autowired
    private KlContentFileInfoMapper klContentFileInfoMapper;

    @Autowired
    private KlContentVerifyLogMapper klContentVerifyLogMapper;

    @Autowired
    private CmsKnowledgeMapper cmsKnowledgeMapper;

    /**
     * 查询知识分类
     * @return 返回知识分类
     * */
    @Override
    public AjaxResult getKnowledgeSortList() {
        List<KnowledgeSortVo> voList = new ArrayList<>();
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        if (CollectionUtils.isEmpty(knowledgeSortList)) {
            return AjaxResult.error("没有数据");
        }
        // 一级
        for (KnowledgeSort knowledgeSort : knowledgeSortList) {
            if ("0".equals(knowledgeSort.getPid())) {
                KnowledgeSortVo vo = new KnowledgeSortVo();
                BeanUtils.copyProperties(knowledgeSort, vo);
                vo.setValue(knowledgeSort.getAutoid());
                vo.setLabel(knowledgeSort.getSortname());
                voList.add(vo);
            }
        }
        voList.sort(Comparator.comparing(person -> person.getOrdernum()));
        // 二级,三级，...
        for (KnowledgeSortVo knowledgeSortVo : voList) {
            findChildren(knowledgeSortVo, knowledgeSortList);
        }
        return AjaxResult.success(voList);
    }

    /**
     * 使用递归，进行分类，由于级数太多了
     * */
    public KnowledgeSortVo findChildren(KnowledgeSortVo vo, List<KnowledgeSort> knowledgeSortLis) {
        for (KnowledgeSort knowledgeSort : knowledgeSortLis) {
            if(vo.getAutoid().equals(knowledgeSort.getPid())) {
                if (vo.getChildren() == null) {
                    vo.setChildren(new ArrayList<KnowledgeSortVo>());
                }
                KnowledgeSortVo threeVo = new KnowledgeSortVo();
                BeanUtils.copyProperties(knowledgeSort, threeVo);
                threeVo.setValue(knowledgeSort.getAutoid());
                threeVo.setLabel(knowledgeSort.getSortname());
                vo.getChildren().add(findChildren(threeVo, knowledgeSortLis));
            }
        }
        if (!CollectionUtils.isEmpty(vo.getChildren())) {
            vo.getChildren().sort(Comparator.comparing(person -> person.getOrdernum()));
        }
        return vo;
    }

    /**
     * 查询知识形式，知识来源
     * @param dictData 字典类型
     * @return
     * */
    @Override
    public List<SysDictData> getKnowledgeShapeList(SysDictData dictData) {
        return dictDataService.selectDictDataList(dictData);
    }

    /**
     * 查询知识
     *
     * @param klId 知识主键
     * @return 知识
     */
    @Override
    public KlContentInfo selectKlContentInfoByKlId(String klId) {
        return klContentInfoMapper.selectKlContentInfoByKlId(klId);
    }

    /**
     * 添加知识数据; 是否案例(1-是；0-不是)
     * @param klContentInfo
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addKlContentInfo(KlContentInfo klContentInfo) {
        // 一些默认值
        // 紧急程度0：一般；1：紧急
        klContentInfo.setKlContentLevel("0");
        // 6 待审核, 1 审核通过, -2 审核未通过, 2 删除待审核
        klContentInfo.setKlContentStatus("6");
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 创建人
        klContentInfo.setKlContentCreater(loginUser.getUserId().toString());
        // 创建人姓名(真实姓名)
        klContentInfo.setKlContentCreaterName(loginUser.getUser().getNickName());
        // 来源:所属组织机构(创建人部门id)
        klContentInfo.setKlContentSources(loginUser.getDeptId().toString());
        // 创建时间
        klContentInfo.setKlContentCreatetime(new Date());
        // 修改时间
        klContentInfo.setKlContentUpdatetime(new Date());
        // 来源方式:1.界面录入2.数据接口3.webservice接口 4.导入文件
        klContentInfo.setKlContentSourcesType("1");
        // 是否上报给12345（0否，1是）
        klContentInfo.setKlContentIshotline("0");
        // 是否置顶（0否，1是）
        klContentInfo.setKlContentIstop("0");
        // 操作类型(知识类型) A-新增 M-修改 D-删除 C-核实
        klContentInfo.setKlContentOpeType(KlContentOpeTypeEnum.A.getKey());
        // 是否删除 0 正常 1删除
        klContentInfo.setKlContentIsDel("0");
        // 核实时间--新增时，该时间就是分布时间
        int day = Integer.parseInt(klContentInfo.getKlUpdateCycle()) - 7;
        klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(klContentInfo.getKlContentPublishtime(), day));
        // 点击量
        klContentInfo.setKlContentHits(0L);
        // 评分
        klContentInfo.setKlContentScore(0.0);
        String klid  = klContentInfoMapper.getKlId();
        klContentInfo.setKlId("SQ" + klid);
        int i = klContentInfoMapper.insertKlContentInfo(klContentInfo);
        if (i > 0) {
            // 建立知识关联文件id
            if (!CollectionUtils.isEmpty(klContentInfo.getFileIdList())) {
                createAssociation(klContentInfo.getFileIdList(), klContentInfo.getKlId());
            }
            addKlContentVerifyLog(klContentInfo.getKlId(), klContentInfo.getKlSortId(), 1);
            addKlOperationsLog("新增知识", JSON.toJSONString(klContentInfo), "成功", null);
            KlContentInfo result = new KlContentInfo();
            result.setKlId(klContentInfo.getKlId());
            result.setKlContentTitle(klContentInfo.getKlContentTitle());
            result.setKlContentKeyword(klContentInfo.getKlContentKeyword());
            return AjaxResult.success(result);
        }
        addKlOperationsLog("新增知识", JSON.toJSONString(klContentInfo), "失败", "新增失败");
        return AjaxResult.error("新增知识失败");
    }

    /**
     * 修改知识数据
     * @param klContentInfo
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateKlContentInfo(KlContentInfo klContentInfo) {
        KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klContentInfo.getKlId());
        if (oldKlContentInfo == null) {
            return AjaxResult.error("传递的知识id错误");
        }
        // 只有知识查询，查无修改知识数据，权限最大，审核通过也可以修改，2023-12-01-我的案例也可以了
        if (!(klContentInfo.getIsCorrection() != null && klContentInfo.getIsCorrection())) {
            // 启动传递的是待审核， 如果查询数据库是审核通过，不允许修改
            if (!KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
                return AjaxResult.error("知识状态：" + KlContentStatusEnum.by(oldKlContentInfo.getKlContentStatus()).getDesc() + "(不允许修改)");
            }
        }
        // 纠错过来的修改/如果知识是审核通过的，修改需要再次审核  查询页面中审核通过要可以修改
        if (!KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
            klContentInfo.setKlContentStatus(KlContentStatusEnum.AUDIT.getKey());
            klContentInfo.setKlContentReviewer("");
        }else {
            // 修改数据时，是不允许修改状态的
            klContentInfo.setKlContentStatus(null);
            if (StringUtils.isNotBlank(oldKlContentInfo.getKlContentReviewer())) {
                // 锁定中，超过15分钟可以修改
                if (System.currentTimeMillis() - oldKlContentInfo.getKlContentReviewertime().getTime() < 15 * 60 * 1000) {
                    return AjaxResult.error("该知识审核中，不允许修改");
                }
            }
        }
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 修改人
        klContentInfo.setKlContentUpdater(loginUser.getUserId().toString());
        // 修改日期
        klContentInfo.setKlContentUpdatetime(new Date());
        // 操作类型(知识类型) A-新增 M-修改 D-删除 C-核实
        klContentInfo.setKlContentOpeType(KlContentOpeTypeEnum.M.getKey());
        // 判断更新周期是否传递
        int day = 0;
        if (StringUtils.isNotBlank(klContentInfo.getKlUpdateCycle())) {
            day = Integer.parseInt(klContentInfo.getKlUpdateCycle()) - 7;
        }else {
            day = Integer.parseInt(oldKlContentInfo.getKlUpdateCycle()) - 7;
        }
        // 判断发布时间是否修改，修改了就以发布时间，为开始时间，推算核实时间
        if (klContentInfo.getKlContentPublishtime() != null) {
            // 两个时间不相等，表示修改了，重新根据发布时间推算核实时间
            if (!klContentInfo.getKlContentPublishtime().equals(oldKlContentInfo.getKlContentPublishtime())) {
                klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(klContentInfo.getKlContentPublishtime(), day));
            }else if (oldKlContentInfo.getKlVerifyTime() != null) {
                // 如果两个时间不相同，可能更新周期修改了，所以根据上
                klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(oldKlContentInfo.getKlVerifyTime(), day));
            }else {
                klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(oldKlContentInfo.getKlContentPublishtime(), day));
            }
        }else {
            if (oldKlContentInfo.getKlVerifyTime() != null) {
                // 如果两个时间不相同，可能更新周期修改了，所以根据上
                klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(oldKlContentInfo.getKlVerifyTime(), day));
            }else {
                klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(oldKlContentInfo.getKlContentPublishtime(), day));
            }
        }
        // 修改知识数据，根据klid修改
        int i = klContentInfoMapper.updateKlContentInfo(klContentInfo);
        if (i > 0) {
            // 建立知识关联文件id
            updateAssociation(klContentInfo.getFileIdList(), klContentInfo.getKlId());
            addKlOperationsLog("修改知识", JSON.toJSONString(klContentInfo), "成功", null);
            return AjaxResult.success("修改成功");
        }
        addKlOperationsLog("修改知识", JSON.toJSONString(klContentInfo), "失败", "修改数据失败");
        return AjaxResult.error("修改失败");
    }

    /**
     * 点击审核按钮--锁定该知识数据
     * @param klContentInfo klId id
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult toExamineKlContentInfo(KlContentInfo klContentInfo) {
        KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klContentInfo.getKlId());
        if (oldKlContentInfo == null) {
            return AjaxResult.error("传递的知识id错误");
        }
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        KlContentInfo newKlContentInfo = new KlContentInfo();
        newKlContentInfo.setKlId(klContentInfo.getKlId());
        // 有人在审核，判断时间是否超过15分钟
        if (StringUtils.isNotBlank(oldKlContentInfo.getKlContentReviewer())) {
            // 判断是否是本人之前在审核：是--修改审核开始时间
            if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                    oldKlContentInfo.getKlContentReviewer().equals(loginUser.getUserId().toString())) {
                newKlContentInfo.setKlContentReviewertime(new Date());
            }else { // 之前不是本人在审核，判断之前审核的人员是否超过了15分钟
                // 判断审核开始时间
                if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                        System.currentTimeMillis() - oldKlContentInfo.getKlContentReviewertime().getTime() > 15 * 60 * 1000) {
                    newKlContentInfo.setKlContentReviewer(loginUser.getUserId().toString());
                    newKlContentInfo.setKlContentReviewertime(new Date());
                }else { // 没有超过15分钟，这个用户不能审核
                    return AjaxResult.error("有用户在审核");
                }
            }
        }else { // 没有人在审核，添加审核人员和审核开始时间
            newKlContentInfo.setKlContentReviewer(loginUser.getUserId().toString());
            newKlContentInfo.setKlContentReviewertime(new Date());
        }
        log.info("a: " + (newKlContentInfo.getKlContentTitle() == null));
        int i = klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
        if (i > 0) {
            addKlOperationsLog("锁定知识审核", JSON.toJSONString(newKlContentInfo), "成功", null);
            return AjaxResult.success("锁定知识成功");
        }
        addKlOperationsLog("锁定知识审核", JSON.toJSONString(newKlContentInfo), "失败", "锁定知识失败");
        return AjaxResult.error("锁定知识失败");
    }

    /**
     * 点击批量审核按钮--锁定这些知识数据-List
     * @param klContentInfo klIdList
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult toExamineKlContentInfoList(KlContentInfo klContentInfo) {
        int toExamineCount = 0;
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        for (String klId : klContentInfo.getKlIdList()) {
            KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klId);
            if (oldKlContentInfo == null) {
                continue;
            }
            KlContentInfo newKlContentInfo = new KlContentInfo();
            newKlContentInfo.setKlId(klId);
            // 有人在审核，判断时间是否超过15分钟
            if (StringUtils.isNotBlank(oldKlContentInfo.getKlContentReviewer())) {
                // 判断是否是本人之前在审核：是--修改审核开始时间
                if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                        oldKlContentInfo.getKlContentReviewer().equals(loginUser.getUserId().toString())) {
                    newKlContentInfo.setKlContentReviewertime(new Date());
                }else { // 之前不是本人在审核，判断之前审核的人员是否超过了15分钟
                    // 判断审核开始时间
                    if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                            System.currentTimeMillis() - oldKlContentInfo.getKlContentReviewertime().getTime() > 15 * 60 * 1000) {
                        newKlContentInfo.setKlContentReviewer(loginUser.getUserId().toString());
                        newKlContentInfo.setKlContentReviewertime(new Date());
                    }else {
                        continue;
                    }
                }
            }else { // 没有人在审核，添加审核人员和审核开始时间
                newKlContentInfo.setKlContentReviewer(loginUser.getUserId().toString());
                newKlContentInfo.setKlContentReviewertime(new Date());
            }
            toExamineCount++;
            klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
        }
        if (toExamineCount == 0) {
            addKlOperationsLog("批量锁定知识审核", JSON.toJSONString(klContentInfo.getKlIdList()), "失败",
                    "选择："+ klContentInfo.getKlIdList().size() + "个，都已经被其他人锁定了");
            return AjaxResult.error("都有人在审核，锁定失败");
        }
        addKlOperationsLog("批量锁定知识审核", JSON.toJSONString(klContentInfo.getKlIdList()), "成功",
                "选择："+ klContentInfo.getKlIdList().size() + "个,批量锁定知识审核成功数量：" + toExamineCount);
        return AjaxResult.success("锁定成功数量：" + toExamineCount);
    }

    /**
     * 审核确定按钮
     * @param klContentInfo klId, klContentStatus
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult toExamineDetermine(KlContentInfo klContentInfo) {
        KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klContentInfo.getKlId());
        if (oldKlContentInfo == null) {
            return AjaxResult.error("传递的知识id错误");
        }
        // 判断传递的审核状态
        if (!(KlContentStatusEnum.APPROVED.getKey().equals(klContentInfo.getKlContentStatus()) ||
                KlContentStatusEnum.REVIEW_FAILED.getKey().equals(klContentInfo.getKlContentStatus()))) {
            return AjaxResult.error("传递的审核状态有误！");
        }
        // 获取当前的用户
        KlContentInfo newKlContentInfo = new KlContentInfo();
        newKlContentInfo.setKlId(klContentInfo.getKlId());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 锁定审核的人是该人员-通过审核
        if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                loginUser.getUserId().toString().equals(oldKlContentInfo.getKlContentReviewer())) {
            newKlContentInfo.setKlContentStatus(klContentInfo.getKlContentStatus());
            newKlContentInfo.setKlContentUpdater(loginUser.getUserId().toString());
            newKlContentInfo.setKlContentUpdatetime(new Date());
            newKlContentInfo.setKlContentIsDel("0");
            klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
            // 添加审核状态，意见日志表
            addKlContentStatusLog(klContentInfo.getKlId(), klContentInfo.getKlContentStatus(),
                    klContentInfo.getReviewComment(), klContentInfo.getKlContentStatus(), KlContentStatusTypeEnum.KNOWLEDGE.getKey());
            // 审核通过
            if (KlContentStatusEnum.APPROVED.getKey().equals(klContentInfo.getKlContentStatus())) {
                addKlOperationsLog("审核通过", JSON.toJSONString(newKlContentInfo), "成功", null);
            }else {
                addKlOperationsLog("审核未通过", JSON.toJSONString(newKlContentInfo), "成功", null);
            }
            return AjaxResult.success("审核-成功");
        }else { // 锁定审核的人不是该人员--不允许通过
            // 审核通过
            if (KlContentStatusEnum.APPROVED.getKey().equals(klContentInfo.getKlContentStatus())) {
                addKlOperationsLog("审核通过", JSON.toJSONString(newKlContentInfo), "失败", "审核时间过长，有其他人在审核了");
            }else {
                addKlOperationsLog("审核未通过", JSON.toJSONString(newKlContentInfo), "失败", "审核时间过长，有其他人在审核了");
            }
            return AjaxResult.error("审核-失败：审核时间过长，有其他人在审核了");
        }
    }

    /**
     * 批量审核确定按钮
     * @param klContentInfo klId, klContentStatus
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult toExamineDetermineList(KlContentInfo klContentInfo) {
        // 判断传递的审核状态是通过或者不通过
        if (!(KlContentStatusEnum.APPROVED.getKey().equals(klContentInfo.getKlContentStatus()) ||
                KlContentStatusEnum.REVIEW_FAILED.getKey().equals(klContentInfo.getKlContentStatus()))) {
            return AjaxResult.error("传递的审核状态有误！");
        }
        int toExamineDetermineCount = 0;
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        for (String klId : klContentInfo.getKlIdList()) {
            KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klId);
            if (oldKlContentInfo == null) {
                continue;
            }
            KlContentInfo newKlContentInfo = new KlContentInfo();
            newKlContentInfo.setKlId(klId);
            // 锁定审核的人是该人员-通过审核
            if (KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus()) &&
                    loginUser.getUserId().toString().equals(oldKlContentInfo.getKlContentReviewer())) {
                newKlContentInfo.setKlContentStatus(klContentInfo.getKlContentStatus());
                newKlContentInfo.setKlContentUpdater(loginUser.getUserId().toString());
                newKlContentInfo.setKlContentUpdatetime(new Date());
                klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
                // 添加审核状态，意见日志表
                addKlContentStatusLog(klId, klContentInfo.getKlContentStatus(),
                        klContentInfo.getReviewComment(), klContentInfo.getKlContentStatus(), KlContentStatusTypeEnum.KNOWLEDGE.getKey());
                toExamineDetermineCount++;
            }else { // 锁定审核的人不是该人员--不允许通过
            }
        }
        // 审核通过--状态
        if (KlContentStatusEnum.APPROVED.getKey().equals(klContentInfo.getKlContentStatus())) {
            if (toExamineDetermineCount == 0) {
                addKlOperationsLog("批量审核通过", JSON.toJSONString(klContentInfo), "失败",
                        "选择："+ klContentInfo.getKlIdList().size() + "个，都已经被其他人审核通过了");
            }else {
                addKlOperationsLog("批量审核通过", JSON.toJSONString(klContentInfo), "成功",
                        "选择："+ klContentInfo.getKlIdList().size() + "个,批量审核通过成功数量：" + toExamineDetermineCount);
            }
        }else { // 审核不通过状态
            if (toExamineDetermineCount == 0) {
                addKlOperationsLog("批量审核未通过", JSON.toJSONString(klContentInfo), "失败",
                        "选择："+ klContentInfo.getKlIdList().size() + "个，都已经被其他人审核未通过了");
            }else {
                addKlOperationsLog("批量审核未通过", JSON.toJSONString(klContentInfo), "成功",
                        "选择："+ klContentInfo.getKlIdList().size() + "个,批量审核不通过成功数量：" + toExamineDetermineCount);
            }
        }
        if (toExamineDetermineCount == 0) {
            return AjaxResult.error("审核-失败,都已经被其他人审核了");
        }
        return AjaxResult.success("批量审核-成功数量：" + toExamineDetermineCount);
    }

    /**
     * 在审核页面，点击返回按钮，解除该知识的锁定
     * @param klContentInfo klid 知识id
     * @return
     * */
    @Override
    public AjaxResult unlockKlContentInfo(KlContentInfo klContentInfo) {
        KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klContentInfo.getKlId());
        if (oldKlContentInfo == null) {
            return AjaxResult.error("传递的知识id错误");
        }
        if (KlContentStatusEnum.APPROVED.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
            return AjaxResult.error(201, "该知识已经审核通过");
        }
        if (StringUtils.isNotBlank(oldKlContentInfo.getKlContentReviewer())) {
            // 获取当前的用户
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser.getUserId().toString().equals(oldKlContentInfo.getKlContentReviewer()) &&
                    KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
                klContentInfoMapper.unlockKlContentInfo(klContentInfo.getKlId());
                addKlOperationsLog("解锁知识", JSON.toJSONString(klContentInfo.getKlId()), "成功", null);
                return AjaxResult.success("解锁知识成功");
            }else {
                return AjaxResult.error("该知识无法解锁");
            }
        }else {
            return AjaxResult.error("没有用户锁定！");
        }
    }

    /**
     * 批量解锁知识
     * @param klContentInfo klidList 知识idList
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult unlockKlContentInfoList(KlContentInfo klContentInfo) {
        int unlockCount = 0;
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        for (String klId : klContentInfo.getKlIdList()) {
            KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klId);
            if (oldKlContentInfo == null) {
                continue;
            }
            if (StringUtils.isNotBlank(oldKlContentInfo.getKlContentReviewer())) {
                if (loginUser.getUserId().toString().equals(oldKlContentInfo.getKlContentReviewer()) &&
                        KlContentStatusEnum.AUDIT.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
                    klContentInfoMapper.unlockKlContentInfo(klId);
                    unlockCount++;
                }
            }
        }
        if (unlockCount == 0) {
            addKlOperationsLog("批量解锁知识", JSON.toJSONString(klContentInfo.getKlIdList()), "失败",
                    "选择："+ klContentInfo.getKlIdList().size() + "个，都解锁失败");
            return AjaxResult.error("批量解锁知识失败");
        }
        addKlOperationsLog("批量解锁知识", JSON.toJSONString(klContentInfo.getKlIdList()), "成功",
                "选择："+ klContentInfo.getKlIdList().size() + "个,批量解锁成功数量：" + unlockCount);
        return AjaxResult.success("批量解锁成功数量：" + unlockCount);
    }

    /**
     * 分页查询知识
     * @param klContentInfo 有模糊查询
     * @return
     * */
    @Override
    public List<KlContentInfo> queryKlContentInfoList(KlContentInfo klContentInfo) {
        List<KlContentInfo> list = klContentInfoMapper.queryKlContentInfoList2(klContentInfo);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        // 查询所有的知识分类List
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        // 查询顶级的3个知识分类List
        KnowledgeSort sort = new KnowledgeSort();
        sort.setPid("0");
        List<KnowledgeSort> sortList = knowledgeSortMapper.selectKnowledgeSortList(sort);
        // 查询所有的部门
        List<SysDept> sysDeptList = deptMapper.selectDeptList(new SysDept());
        // 所有用户
        List<SysUser> sysUserList = userMapper.selectUserList(new SysUser());
        // 查询所有的知识形式
        SysDictData dictData = new SysDictData();
        dictData.setDictType("knowledge_shape");
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
        for (KlContentInfo info : list) {
            // 用户信息
            for (SysUser sysUser : sysUserList) {
                if (sysUser.getUserId().toString().equals(info.getKlContentCreater())) {
                    info.setUserName(sysUser.getUserName());
                    info.setRealName(sysUser.getNickName());
//                    info.setSysUser(sysUser);
                    break;
                }
            }
            // 部门信息
            for (SysDept sysDept : sysDeptList) {
                if (sysDept.getDeptId().toString().equals(info.getKlContentSources())) {
//                    info.setSysDept(sysDept);
                    info.setKlContentSourcesName(sysDept.getDeptName());
                    break;
                }
            }
            // 知识分类
            if (StringUtils.isNotBlank(info.getKlSortId())) {
                for (KnowledgeSort knowledgeSort : knowledgeSortList) {
                    if (info.getKlSortId().equals(knowledgeSort.getAutoid())) {
                        String klSortName = knowledgeSort.getSortname();
                        for (KnowledgeSort sort1 : sortList) {
                            if (knowledgeSort.getPid().equals(sort1.getAutoid())) {
                                klSortName = sort1.getSortname() + "/" + klSortName;
                            }
                        }
                        info.setKlSortName(klSortName);
                        break;
                    }
                }
            }
            // 知识形式
            for (SysDictData sysDictData : sysDictDataList) {
                if (sysDictData.getDictValue().equals(info.getKlContentType())) {
                    info.setKlContentTypeDesc(sysDictData.getDictLabel());
                    break;
                }
            }
            info.setKlContentStatusDesc(KlContentStatusEnum.by(info.getKlContentStatus()).getDesc());
            // 判断是否失效
            if (info.getKlContentValiditytime() != null &&
                    info.getKlContentValiditytime().getTime() - System.currentTimeMillis() < 0) {
                info.setIsLoseEfficacy(true);
                info.setIsLoseEfficacyDesc("否");
            }
            /** 是否删除 0 正常-否 1删除-是 */
            if ("1".equals(info.getKlContentIsDel())) {
                info.setKlContentIsDelDesc("是");
            }
            // 操作类型 A 新增 M修改 D删除 C核实
            info.setKlContentOpeTypeDesc(KlContentOpeTypeEnum.by(info.getKlContentOpeType()).getDesc());
            if (StringUtils.isNotBlank(info.getKlContent())) {
                info.setKlContent(filterHtml(info.getKlContent()));
            }
            // 查询最新一条审核意见---待审核的不查询
            if (!info.getKlContentStatus().equals(KlContentStatusEnum.AUDIT.getKey())) {
                // 审批记录数据
                KlContentStatusLog klContentStatusLog = new KlContentStatusLog();
                klContentStatusLog.setKlId(info.getKlId());
                klContentStatusLog.setStatusType(KlContentStatusTypeEnum.KNOWLEDGE.getKey());
                List<KlContentStatusLog> statusLogs = klContentStatusLogMapper.queryKlContentStatusLogListAsc(klContentStatusLog);
                if (!CollectionUtils.isEmpty(statusLogs)) {
                    KlContentStatusLog statusLog = statusLogs.get(statusLogs.size() - 1);
                    if (StringUtils.isNotBlank(statusLog.getReviewComment())) {
                        info.setReviewComment(statusLog.getReviewComment());
                        info.setReviewName(statusLog.getRealName());
                    }
                }
            }
        }
        return list;
    }

    /**
     * 根据id查询知识数据
     * @param klId 知识表id
     * @return
     * */
    @Override
    public KlContentInfo queryKlContentInfoByKlId(String klId) {
        KlContentInfo klContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klId);
        if (klContentInfo == null) {
            return null;
        }
        if (StringUtils.isNotBlank(klContentInfo.getKlContentCreater())) {
            SysUser sysUser = userMapper.selectUserById(Long.parseLong(klContentInfo.getKlContentCreater()));
            if (sysUser != null) {
                klContentInfo.setUserName(sysUser.getUserName());
                klContentInfo.setRealName(sysUser.getNickName());
                klContentInfo.setSysUser(sysUser);
            }
        }
        // 知识分类
        if (StringUtils.isNotBlank(klContentInfo.getKlSortId())) {
            KnowledgeSort knowledgeSort = knowledgeSortMapper.selectKnowledgeSortByAutoid(klContentInfo.getKlSortId());
            if (knowledgeSort != null) {
                klContentInfo.setKlSortName(knowledgeSort.getSortname());
            }
        }
        // 查询关联的知识数据
        if (StringUtils.isNotBlank(klContentInfo.getKlKnowledgeCorrelationId())) {
            String[] array = klContentInfo.getKlKnowledgeCorrelationId().split(",");
            klContentInfo.setKlKnowledgeCorrelationList(klContentInfoMapper.queryKlContentInfoByKlIds(Arrays.asList(array)));
        }
        // 判断是否失效
        if (klContentInfo.getKlContentValiditytime() != null &&
                klContentInfo.getKlContentValiditytime().getTime() - System.currentTimeMillis() < 0) {
            klContentInfo.setIsLoseEfficacy(true);
        }
        // 审批记录数据
        KlContentStatusLog klContentStatusLog = new KlContentStatusLog();
        klContentStatusLog.setKlId(klContentInfo.getKlId());
        klContentStatusLog.setStatusType(KlContentStatusTypeEnum.KNOWLEDGE.getKey());
        List<KlContentStatusLog> statusLogs = klContentStatusLogMapper.queryKlContentStatusLogListAsc(klContentStatusLog);
        if (!CollectionUtils.isEmpty(statusLogs)) {
            klContentInfo.setStatusLogList(statusLogs);
        }
        // 来源:所属组织机构 ---部门id
        if (StringUtils.isNotBlank(klContentInfo.getKlContentSources())) {
            SysDept sysDept = deptMapper.selectDeptById(Long.parseLong(klContentInfo.getKlContentSources()));
            if (sysDept != null) {
                klContentInfo.setKlContentSourcesName(sysDept.getDeptName());
                klContentInfo.setSysDept(sysDept);
            }
        }
        // 6 待审核, 1 审核通过, -2 审核未通过, 2 删除待审核
        klContentInfo.setKlContentStatusDesc(KlContentStatusEnum.by(klContentInfo.getKlContentStatus()).getDesc());
        // 评价人数
        KlContentScoreLog klContentScoreLog = new KlContentScoreLog();
        klContentScoreLog.setKlId(klId);
        int count = klContentScoreLogMapper.countKlContentScoreLog(klContentScoreLog);
        klContentInfo.setScoreNumber(count);
        // 查询关联的文件
        KlContentFileInfo klContentFileInfo = new KlContentFileInfo();
        klContentFileInfo.setKlContentId(klId);
        klContentFileInfo.setKlFileIsDel("0");
        List<KlContentFileInfo> fileInfoList = klContentFileInfoMapper.selectKlContentFileInfoList(klContentFileInfo);
        if (!CollectionUtils.isEmpty(fileInfoList)) {
            klContentInfo.setFileList(fileInfoList);
        }
        // 操作类型 A 新增 M修改 D删除
        klContentInfo.setKlContentOpeTypeDesc(KlContentOpeTypeEnum.by(klContentInfo.getKlContentOpeType()).getDesc());
        // 查询cms知识附件
        LambdaQueryWrapper<CmsKnowledge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CmsKnowledge::getKlId, klId);
        CmsKnowledge cmsKnowledge = cmsKnowledgeMapper.selectOne(queryWrapper);
        if (cmsKnowledge != null && StringUtils.isNotBlank(cmsKnowledge.getZwPdfUrl())) {
            klContentInfo.setZwPDFUrl(cmsKnowledge.getZwPdfUrl());
            klContentInfo.setZwPDFName(cmsKnowledge.getZwPdfName());
        }
        return klContentInfo;
    }

    /**
     * 查询更新周期7天前的知识，审核通过的, 过期的不查询--添加时计算出来，加一个字段：下一次更新开始时间
     * 当前时间 > 发布时间 + 半年 - 7天 ; 查询出来
     * 已失效的不查询
     * @param klContentInfo
     * @return
     * */
    @Override
    public List<KlContentInfo> queryUpdateCycleKlContent(KlContentInfo klContentInfo) {
        klContentInfo.setKlContentStatus(KlContentStatusEnum.APPROVED.getKey());
        // 根据开始是判断，开始核实时间大于当前时间，查询出来
        klContentInfo.setKlStartVerifyTime(new Date());
        // 有效期，当前时间大于有效期时间，不查询出来
        klContentInfo.setKlContentValiditytime(new Date());
        klContentInfo.setKlContentIsDel("0");
        List<KlContentInfo> list = klContentInfoMapper.queryKlContentInfoList2(klContentInfo);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        // 查询所有的知识分类List
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        // 查询顶级的3个知识分类List
        KnowledgeSort sort = new KnowledgeSort();
        sort.setPid("0");
        List<KnowledgeSort> sortList = knowledgeSortMapper.selectKnowledgeSortList(sort);
        // 查询所有的部门
        List<SysDept> sysDeptList = deptMapper.selectDeptList(new SysDept());
        // 查询所有的知识形式
        SysDictData dictData = new SysDictData();
        dictData.setDictType("knowledge_shape");
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
        for (KlContentInfo info : list) {
            // 部门信息
            for (SysDept sysDept : sysDeptList) {
                if (sysDept.getDeptId().toString().equals(info.getKlContentSources())) {
                    info.setKlContentSourcesName(sysDept.getDeptName());
                    break;
                }
            }
            // 知识分类
            if (StringUtils.isNotBlank(info.getKlSortId())) {
                for (KnowledgeSort knowledgeSort : knowledgeSortList) {
                    if (info.getKlSortId().equals(knowledgeSort.getAutoid())) {
                        String klSortName = knowledgeSort.getSortname();
                        for (KnowledgeSort sort1 : sortList) {
                            if (knowledgeSort.getPid().equals(sort1.getAutoid())) {
                                klSortName = sort1.getSortname() + "/" + klSortName;
                            }
                        }
                        info.setKlSortName(klSortName);
                        break;
                    }
                }
            }
            // 知识形式
            for (SysDictData sysDictData : sysDictDataList) {
                if (sysDictData.getDictValue().equals(info.getKlContentType())) {
                    info.setKlContentTypeDesc(sysDictData.getDictLabel());
                    break;
                }
            }
            info.setKlContentStatusDesc(KlContentStatusEnum.by(info.getKlContentStatus()).getDesc());
            // 判断是否失效
            if (info.getKlContentValiditytime().getTime() - System.currentTimeMillis() < 0) {
                info.setIsLoseEfficacy(true);
                info.setIsLoseEfficacyDesc("否");
            }
            /** 是否删除 0 正常-否 1删除-是 */
            if ("1".equals(info.getKlContentIsDel())) {
                info.setKlContentIsDelDesc("是");
            }
            // 操作类型 A 新增 M修改 D删除
            info.setKlContentOpeTypeDesc(KlContentOpeTypeEnum.by(info.getKlContentOpeType()).getDesc());
        }
        return list;
    }

    /**
     * 更新周期时间到了，进行修改（核实--不修改状态，处理--修改知识状态，重新走一遍审核流程）
     * 修改更新周期的时间
     * @param klContentInfo
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateCycleKlContent(KlContentInfo klContentInfo) {
        KlContentInfo oldKlContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klContentInfo.getKlId());
        if (oldKlContentInfo == null) {
            return AjaxResult.error("知识库不存在");
        }
        if (!KlContentStatusEnum.APPROVED.getKey().equals(oldKlContentInfo.getKlContentStatus())) {
            return AjaxResult.error("该知识不是审核通过");
        }
        // 核实时间--新增，该时间就是发布时间
        klContentInfo.setKlVerifyTime(new Date());
        int day = 0;
        // 修改了更新周期
        if (StringUtils.isNotBlank(klContentInfo.getKlUpdateCycle())) {
            day = Integer.parseInt(klContentInfo.getKlUpdateCycle()) - 7;
        }else {
            day = Integer.parseInt(oldKlContentInfo.getKlUpdateCycle()) - 7;
        }
        klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(klContentInfo.getKlVerifyTime(), day));
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 修改人
        klContentInfo.setKlContentUpdater(loginUser.getUserId().toString());
        // 修改日期
        klContentInfo.setKlContentUpdatetime(new Date());
        // 操作类型(知识类型) A-新增 M-修改 D-删除 C-核实
        klContentInfo.setKlContentOpeType(KlContentOpeTypeEnum.C.getKey());
        // ERIFY:核实；HANDLE：处理---处理需要重新走一遍审核流程
        if ("HANDLE".equals(klContentInfo.getClickType())) {
            // 审核-修改--知识状态到，--待审核
            klContentInfo.setKlContentStatus(KlContentStatusEnum.AUDIT.getKey());
        }
        int i = klContentInfoMapper.updateKlContentInfo(klContentInfo);
        if (i > 0) {
            // ERIFY:核实；HANDLE：处理
            if (StringUtils.isNotBlank(klContentInfo.getKlSortId())) {
                addKlContentVerifyLog(klContentInfo.getKlId(), klContentInfo.getKlSortId(), 2);
            }else {
                addKlContentVerifyLog(klContentInfo.getKlId(), oldKlContentInfo.getKlSortId(), 2);
            }
            addKlOperationsLog("知识核实", JSON.toJSONString(klContentInfo), "成功", null);
            return AjaxResult.success("操作成功");
        }
        addKlOperationsLog("知识核实", JSON.toJSONString(klContentInfo), "失败", "核实修改失败");
        return AjaxResult.error("操作失败！");
    }

    /**
     * 知识库检索接口, 分页查询
     * @param query
     * @return
     * */
    @Override
    public List<KlContentInfo> retrievalKlContentInfo(KlContentInfoQuery query) {
        KlContentInfo klContentInfo = new KlContentInfo();
        // 检索字段
        if (!CollectionUtils.isEmpty(query.getSearchType())) {
            for (String type : query.getSearchType()) {
                // 标题
                if (KlContentSearchTypeEnum.KL_TITLE.getKey().equals(type)) {
                    klContentInfo.setKlContentTitle(query.getSearchContent());
                // 知识内容
                }else if (KlContentSearchTypeEnum.KL_CONTENT.getKey().equals(type)) {
                    klContentInfo.setKlContent(query.getSearchContent());
                // 关键字
                }else if (KlContentSearchTypeEnum.KL_KEYWORD.getKey().equals(type)) {
                    klContentInfo.setKlContentKeyword(query.getSearchContent());
                }
            }
        }else {
            klContentInfo.setKlContentTitle(query.getSearchContent());
            klContentInfo.setKlContent(query.getSearchContent());
            klContentInfo.setKlContentKeyword(query.getSearchContent());
        }
        // 分类id List
        if (!CollectionUtils.isEmpty(query.getKlSortIdList())) {
            // 查询全部的分类
            List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
            Set<String> klSortIdSet = new HashSet<>();
            for (String klSortId : query.getKlSortIdList()) {
                klSortIdSet.add(klSortId);
                findQueryChildren(klSortId, knowledgeSortList, klSortIdSet);
            }
            List<String> klSortIds = new ArrayList<>();
            klSortIds.addAll(klSortIdSet);
            klContentInfo.setKlSortIdList(klSortIds);
        }
        // 知识形式
        if (StringUtils.isNotBlank(query.getKlContentType())) {
            klContentInfo.setKlContentType(query.getKlContentType());
        }
        // 1 审核通过
        klContentInfo.setKlContentStatus(KlContentStatusEnum.APPROVED.getKey());
        // 排序策略
        if (StringUtils.isNotBlank(query.getSortType())) {
            klContentInfo.setSortType(query.getSortType());
        }
        PageUtils.startPage();
        List<KlContentInfo> klContentInfoList = klContentInfoMapper.retrievalKlContentInfo(klContentInfo);
        for (KlContentInfo info : klContentInfoList) {
            if (StringUtils.isNotBlank(info.getKlContent())) {
                info.setKlContent(filterHtml(info.getKlContent()));
            }
        }
        return klContentInfoList;
    }

    /**
     * 使用递归，进行分类，由于级数太多了
     * */
    public void findQueryChildren(String klSortId, List<KnowledgeSort> knowledgeSortLis,  Set<String> klSortIdList) {
        for (KnowledgeSort knowledgeSort : knowledgeSortLis) {
            if(klSortId.equals(knowledgeSort.getPid())) {
                klSortIdList.add(knowledgeSort.getAutoid());
                findQueryChildren(knowledgeSort.getAutoid(), knowledgeSortLis, klSortIdList);
            }
        }
    }

    /**
     * 加点击量
     * @param klId 知识id
     * @return
     * */
    @Override
    public int plusKlContentHits(String klId) {
        KlContentInfo klContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(klId);
        if (klContentInfo == null) {
            return 0;
        }
        KlContentInfo newKlContentInfo = new KlContentInfo();
        newKlContentInfo.setKlId(klId);
        newKlContentInfo.setKlContentHits(klContentInfo.getKlContentHits() + 1);
        newKlContentInfo.setUpdateTime(new Date());
        return klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
    }

    /**
     * 提交评分
     * @param query 知识id，评分
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult submitScore(KlContentInfoQuery query) {
        KlContentInfo klContentInfo = klContentInfoMapper.selectKlContentInfoByKlId(query.getKlId());
        if (klContentInfo == null) {
            return AjaxResult.error("知识id不存在");
        }
        KlContentScoreLog klContentScoreLog = new KlContentScoreLog();
        klContentScoreLog.setKlId(query.getKlId());
        List<KlContentScoreLog> scoreLogList = klContentScoreLogMapper.selectKlContentScoreLogList(klContentScoreLog);
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 添加的参数
        klContentScoreLog.setUserId(loginUser.getUserId().toString());
        klContentScoreLog.setKlScore(query.getKlScore());
        klContentScoreLog.setCreateTime(new Date());
        // 知识参数
        KlContentInfo newKlContentInfo = new KlContentInfo();
        newKlContentInfo.setKlId(query.getKlId());
        newKlContentInfo.setUpdateTime(new Date());
        // 第一次评分
        if (CollectionUtils.isEmpty(scoreLogList)) {
            klContentScoreLogMapper.insertKlContentScoreLog(klContentScoreLog);
            newKlContentInfo.setKlContentScore(Double.parseDouble(query.getKlScore().toString()));
            klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
            return AjaxResult.success("评分成功");
        }else {
            Long num = scoreLogList.stream().collect(Collectors.summingLong(KlContentScoreLog::getKlScore));
            num = num + query.getKlScore();
            int peopleNumber = scoreLogList.size() + 1;
            BigDecimal score = new BigDecimal(num).divide(new BigDecimal(peopleNumber), 1, BigDecimal.ROUND_HALF_UP);
            klContentScoreLogMapper.insertKlContentScoreLog(klContentScoreLog);
            newKlContentInfo.setKlContentScore(Double.parseDouble(score.toString()));
            klContentInfoMapper.updateKlContentInfo(newKlContentInfo);
            return AjaxResult.success("评分成功");
        }
    }

    /**
     * 首页查询10审核通过的知识数据展示
     * @param klContentInfo
     * @return
     * */
    @Override
    public List<KlContentInfo> queryHomeKlContentInfoList(KlContentInfo klContentInfo) {
        List<KnowledgeSort> knowledgeSortList = null;
        KnowledgeSort knowledgeSort = new KnowledgeSort();
        if (StringUtils.isNotBlank(klContentInfo.getKlSortId())) {
            knowledgeSort.setPid(klContentInfo.getKlSortId());
            knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(knowledgeSort);
        }
        if (!CollectionUtils.isEmpty(knowledgeSortList)) {
            List<String> sortIdList = knowledgeSortList.stream().map(KnowledgeSort::getAutoid).collect(Collectors.toList());
            sortIdList.add(klContentInfo.getKlSortId());
            klContentInfo.setKlSortIdList(sortIdList);
        }
//        klContentInfo.setKlContentStatus(KlContentStatusEnum.APPROVED.getKey());
        klContentInfo.setKlContentValiditytime(new Date());
        PageUtils.startPage();
        List<KlContentInfo> list = klContentInfoMapper.queryHomeKlContentInfoList(klContentInfo);
        for (KlContentInfo info : list) {
            if (StringUtils.isNotBlank(info.getKlContent())) {
                info.setKlContent(filterHtml(info.getKlContent()));
            }
        }
        return list;
    }

    @Override
    public List<KlContentInfo> queryHomeListOrderByUpdateTime(KlContentInfo klContentInfo) {
        List<KnowledgeSort> knowledgeSortList = null;
        KnowledgeSort knowledgeSort = new KnowledgeSort();
        if (StringUtils.isNotBlank(klContentInfo.getKlSortId())) {
            knowledgeSort.setPid(klContentInfo.getKlSortId());
            knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(knowledgeSort);
        }
        if (!CollectionUtils.isEmpty(knowledgeSortList)) {
            List<String> sortIdList = knowledgeSortList.stream().map(KnowledgeSort::getAutoid).collect(Collectors.toList());
            sortIdList.add(klContentInfo.getKlSortId());
            klContentInfo.setKlSortIdList(sortIdList);
        }
        klContentInfo.setKlContentValiditytime(new Date());
        PageUtils.startPage();
        List<KlContentInfo> list = klContentInfoMapper.queryHomeListOrderByUpdateTime(klContentInfo);
        for (KlContentInfo info : list) {
            if (StringUtils.isNotBlank(info.getKlContent())) {
                info.setKlContent(filterHtml(info.getKlContent()));
            }
        }
        return list;
    }

    @Override
    public List<KlContentInfoCountVo> countByKnowledgeSortPid(String pid) {
        return klContentInfoMapper.countByKnowledgeSortPid(pid);
    }

    /**
     * 导入知识库数据
     * @param excelList 生产文件
     * @return
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult importKlContentInfoExcel(List<KlContentInfoExcel> excelList) {
        // 查询所有的知识分类List
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        // 查询所有的知识形式
        SysDictData dictData = new SysDictData();
        dictData.setDictType("knowledge_shape");
        List<SysDictData> shapeList = dictDataService.selectDictDataList(dictData);
        // 查询所有知识来源
        dictData.setDictType("knowledge_source");
        List<SysDictData> sourceList = dictDataService.selectDictDataList(dictData);
        // 查询关联的知识
        List<KlContentInfo> associationKlList = getAssociationKlList(excelList);
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<KlContentInfo> klContentInfoList = new ArrayList<>();
        // 从第2条数据开始，第一条数据是备注
        for (int i = 0; i < excelList.size(); i++) {
            int lineNumber = i + 3;
            KlContentInfoExcel excel = excelList.get(i);
            /**先判断必填的字段是否是空*/
            String msg = judgmentNotNull(excel, lineNumber);
            if (StringUtils.isNotBlank(msg)) {
                return AjaxResult.error(msg);
            }
            KlContentInfo klContentInfo = new KlContentInfo();
            // 一级分类名称--是否填写正确
            List<String> oneSortIdList = new ArrayList<>();
            for (KnowledgeSort sort : knowledgeSortList) {
                if (excel.getOneSortName().trim().equals(sort.getSortname())) {
                    oneSortIdList.add(sort.getAutoid());
                }
            }
            if (CollectionUtils.isEmpty(oneSortIdList)) {
                return AjaxResult.error("第" + lineNumber + "行：一级分类名称: " + excel.getOneSortName() + "-不存在");
            }
            // 二级分类名称--是否填写正确
            String klSortId = null;
            for (String oneSortId : oneSortIdList) {
                for (KnowledgeSort sort : knowledgeSortList) {
                    if (excel.getTwoSortName().trim().equals(sort.getSortname()) && oneSortId.equals(sort.getPid())) {
                        klSortId = sort.getAutoid();
                        break;
                    }
                }
            }
            if (StringUtils.isBlank(klSortId)) {
                return AjaxResult.error("第" + lineNumber + "行：二级分类名称: " + excel.getTwoSortName() + "-不存在");
            }
            klContentInfo.setKlSortId(klSortId);
            // 知识形式
            String klContentType = null;
            for (SysDictData shape : shapeList) {
                if (excel.getKlContentTypeName().trim().equals(shape.getDictLabel())) {
                    klContentType = shape.getDictValue();
                }
            }
            if (StringUtils.isBlank(klContentType)) {
                return AjaxResult.error("第" + lineNumber + "行：知识形式: " + excel.getKlContentTypeName().trim() + "-不存在");
            }
            klContentInfo.setKlContentType(klContentType);
            // 知识来源
            String klContentBelongUnit = null;
            for (SysDictData source: sourceList) {
                if (source.getDictLabel().equals(excel.getKlContentBelongUnit().trim())) {
                    klContentBelongUnit = source.getDictValue();
                }
            }
            if (StringUtils.isBlank(klContentBelongUnit)) {
                return AjaxResult.error("第" + lineNumber + "行：知识来源: " + excel.getKlContentBelongUnit().trim() + "-不存在");
            }
            klContentInfo.setKlContentBelongUnit(klContentBelongUnit);
            // set  标题，知识内容，关键字，发布日期，有效期，是否热点，政策文号，相关工单编号，总条数
            setPartParam(klContentInfo, excel);
            // set 关联知识 List
            setKnowledgeCorrelationId(klContentInfo, excel, associationKlList);
            // 设置一些默认值
            setDefaultKlContentInfo(klContentInfo, loginUser);
            klContentInfoList.add(klContentInfo);
        }
        int count = 0;
        for (KlContentInfo klContentInfo : klContentInfoList) {
            int i = klContentInfoMapper.insertKlContentInfo(klContentInfo);
            if (i > 0) {
                count++;
            }
        }
        return AjaxResult.success("成功数量: " + count);
    }

    /**
     * set  标题，知识内容，关键字，发布日期，有效期，是否热点，政策文号，相关工单编号，总条数
     * */
    private void setPartParam(KlContentInfo klContentInfo, KlContentInfoExcel excel) {
        // 标题
        klContentInfo.setKlContentTitle(excel.getKlContentTitle().trim());
        // 知识内容
        klContentInfo.setKlContent(excel.getKlContent().trim());
        // 关键字
        klContentInfo.setKlContentKeyword(excel.getKlContentKeyword().trim());
        // 发布日期
        if (excel.getKlContentPublishtime() == null) {
            klContentInfo.setKlContentPublishtime(new Date());
        }else {
            klContentInfo.setKlContentPublishtime(excel.getKlContentPublishtime());
        }
        // 有效期
        if (excel.getKlContentValiditytime() == null) {
            klContentInfo.setKlContentValiditytime(DateUtils.parseDate("2100-01-01"));
        }else {
            klContentInfo.setKlContentValiditytime(excel.getKlContentValiditytime());
        }
        // 是否热点
        if (StringUtils.isNotBlank(excel.getKlContentIshot())) {
            if ("是".equals(excel.getKlContentIshot().trim())) {
                klContentInfo.setKlContentIshot("1");
            }else {
                klContentInfo.setKlContentIshot("0");
            }
        }
        // 政策文号
        if (StringUtils.isNotBlank(excel.getPolicyNo())) {
            klContentInfo.setPolicyNo(excel.getPolicyNo().trim());
        }
        // 相关工单编号
        if (StringUtils.isNotBlank(excel.getRelWpid())) {
            klContentInfo.setRelWpid(excel.getRelWpid().trim());
        }
        // 总条数
        if (StringUtils.isNotBlank(excel.getKlTotal())) {
            klContentInfo.setKlTotal(excel.getKlTotal().trim());
        }
    }

    /**
     *  获取上传知识中所有的关联知识List
     * */
    private List<KlContentInfo> getAssociationKlList(List<KlContentInfoExcel> excelList) {
        Set<String> klTitleSet = new HashSet<>();
        for (KlContentInfoExcel excel : excelList) {
            if (StringUtils.isNotBlank(excel.getKlTitleName1())) {
                klTitleSet.add(excel.getKlTitleName1().trim());
            }
            if (StringUtils.isNotBlank(excel.getKlTitleName2())) {
                klTitleSet.add(excel.getKlTitleName2().trim());
            }
            if (StringUtils.isNotBlank(excel.getKlTitleName3())) {
                klTitleSet.add(excel.getKlTitleName3().trim());
            }
        }
        List<KlContentInfo> associationKlList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(klTitleSet)) {
            List<String> klTitleList = new ArrayList<>();
            klTitleList.addAll(klTitleSet);
            // 查询关联知识
            KlContentInfo klContentInfo = new KlContentInfo();
            klContentInfo.setKlTitleList(klTitleList);
            klContentInfo.setKlContentStatus(KlContentStatusEnum.APPROVED.getKey());
            klContentInfo.setKlContentIsDel("0");
            associationKlList = klContentInfoMapper.queryKlContentInfoByTitle(klContentInfo);
        }
        return associationKlList;
    }

    /**
     *  set 关联知识 List
     * */
    private void setKnowledgeCorrelationId(KlContentInfo klContentInfo, KlContentInfoExcel excel, List<KlContentInfo> associationKlList) {
        // 关联的知识标题
        if (associationKlList.size() > 0) {
            List<String> klIdList = new ArrayList<>();
            for (KlContentInfo info : associationKlList) {
                // 知识关联1
                if (StringUtils.isNotBlank(excel.getKlTitleName1()) && excel.getKlTitleName1().trim().equals(info.getKlContentTitle())) {
                    klIdList.add(info.getKlId());
                    excel.setKlTitleName1("");
                    continue;
                }
                // 知识关联2
                if (StringUtils.isNotBlank(excel.getKlTitleName2()) && excel.getKlTitleName2().trim().equals(info.getKlContentTitle())) {
                    klIdList.add(info.getKlId());
                    excel.setKlTitleName2("");
                    continue;
                }
                // 知识关联3
                if (StringUtils.isNotBlank(excel.getKlTitleName3()) && excel.getKlTitleName3().trim().equals(info.getKlContentTitle())) {
                    klIdList.add(info.getKlId());
                    excel.setKlTitleName3("");
                    continue;
                }
            }
            if (!CollectionUtils.isEmpty(klIdList)) {
                StringBuffer klKnowledgeCorrelationId = new StringBuffer();
                for (int j = 0; j < klIdList.size(); j++) {
                    if (j == 0) {
                        klKnowledgeCorrelationId.append(klIdList.get(j));
                    }else {
                        klKnowledgeCorrelationId.append("," + klIdList.get(j));
                    }
                }
                klContentInfo.setKlKnowledgeCorrelationId(klKnowledgeCorrelationId.toString());
            }
        }
    }

    /**
     * 根据知识分类统计知识添加数量，核实数量
     * @param query
     * @return
     * */
    @Override
    public List<KlContentInfoCountVo> countVerifyKlContentInfo(KlContentInfoQuery query) {
        List<KlContentInfoCountVo> list = new ArrayList<>();
        // 查询新增知识统计数量
        query.setKlType(1);
        List<KlContentInfoCountVo> addCountVoList = klContentVerifyLogMapper.countVerifyKlContentInfo(query);
        // 查询核实知识统计数据
        query.setKlType(2);
        List<KlContentInfoCountVo> verifyCountVoList = klContentVerifyLogMapper.countVerifyKlContentInfo(query);
        if (CollectionUtils.isEmpty(addCountVoList) && CollectionUtils.isEmpty(verifyCountVoList)) {
            return list;
        }
        Map<String, String> countSortMap = new HashMap<>();
        Map<String, KlContentInfoCountVo> addCountMap = new HashMap<>();
        addCountVoList.stream().forEach(vo -> {
            countSortMap.put(vo.getKlSortId(), "");
            addCountMap.put(vo.getKlSortId(), vo);
        });
        Map<String, KlContentInfoCountVo> verifyCountMap = new HashMap<>();
        verifyCountVoList.stream().forEach(vo -> {
            countSortMap.put(vo.getKlSortId(), "");
            verifyCountMap.put(vo.getKlSortId(), vo);
        });
        List<KnowledgeSort> knowledgeSortList = knowledgeSortMapper.selectKnowledgeSortList(new KnowledgeSort());
        countSortMap.entrySet().forEach(sort ->{
            String klSortId = sort.getKey();
            KlContentInfoCountVo countVo = new KlContentInfoCountVo(klSortId);
            // 查询知识分类名称
            for (KnowledgeSort knowledgeSort : knowledgeSortList) {
                if (knowledgeSort.getAutoid().equals(klSortId)) {
                    countVo.setKlSortName(knowledgeSort.getSortname());
                    break;
                }
            }
            KlContentInfoCountVo addVo = addCountMap.get(klSortId);
            if (addVo != null ) {
                countVo.setAddKnowledgeCount(addVo.getTypeCount());
            }
            KlContentInfoCountVo verifyVo = verifyCountMap.get(klSortId);
            if (verifyVo != null) {
                countVo.setVerifyCount(verifyVo.getTypeCount());
            }
            list.add(countVo);
        });
        return list;
    }

    /**
     * 工单模块：分页查询知识
     * @param klContentInfo 知识标题
     * @return 返回：知识标题，知识内容
     * */
    @Override
    public List<KlContentInfo> queryWpKlContentInfoList(KlContentInfo klContentInfo) {
        return klContentInfoMapper.queryKlContentInfoList(klContentInfo);
    }

    @Override
    public int deleteKlContentInfoByKlId(KlContentInfo klContentInfo) {
        return klContentInfoMapper.deleteKlByKlId(klContentInfo.getKlId());
    }

    @Override
    public int deleteByKlId(String klId) {
        return klContentInfoMapper.deleteByKlId(klId);
    }


    /**
     * 添加审批状态日志
     * @param klId 知识表id
     * @param klContentStatus 审批状态;1 审核通过, -2 审核未通过
     * @param reviewComment 审批意见
     *  */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addKlContentStatusLog(String klId, String klContentStatus, String reviewComment,
                                      String processAfterState, String statusType) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        KlContentStatusLog klContentStatusLog = new KlContentStatusLog();
        klContentStatusLog.setKlId(klId);
        klContentStatusLog.setContentStatus(klContentStatus);
        klContentStatusLog.setReviewComment(reviewComment);
        klContentStatusLog.setUserId(loginUser.getUserId().toString());
        klContentStatusLog.setUserName(loginUser.getUsername());
        klContentStatusLog.setRealName(loginUser.getUser().getNickName());
        klContentStatusLog.setCreateTime(new Date());
        klContentStatusLog.setProcessAfterState(processAfterState);
        klContentStatusLog.setStatusType(statusType);
        klContentStatusLogMapper.insertKlContentStatusLog(klContentStatusLog);
    }


    /**
     * 添加知识操作日志方法
     * */
    @Override
    public void addKlOperationsLog(String operationsType, String param, String result, String failureReason) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 单独线程添加操作日志
        new Thread(new Runnable() {
            @Override
            public void run() {
                KlOperationsLog klOperationsLog = new KlOperationsLog();
                klOperationsLog.setUsetId(loginUser.getUserId().toString());
                klOperationsLog.setUserName(loginUser.getUsername());
                klOperationsLog.setOperationsTime(new Date());
                klOperationsLog.setOperationsType(operationsType);
                if (StringUtils.isNotBlank(param)) {
                    klOperationsLog.setParam(param);
                }
                klOperationsLog.setResult(result);
                if (StringUtils.isNotBlank(failureReason)) {
                    klOperationsLog.setFailureReason(failureReason);
                }
                klOperationsLogMapper.insertKlOperationsLog(klOperationsLog);
            }
        }).start();

    }

    /**
     * 建立知识/查无/纠错和文件的管理
     * @param fileIdList
     * @param klContentId
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createAssociation(List<String> fileIdList, String klContentId) {
        // 建立知识关联文件id
        if (!CollectionUtils.isEmpty(fileIdList)) {
            KlContentFileInfo klContentFileInfo = new KlContentFileInfo();
            // 关联知识id
            klContentFileInfo.setKlContentId(klContentId);
            // 文件id
            klContentFileInfo.setKlIds(fileIdList);
            klContentFileInfoMapper.updateKlContentFileInfoByIds(klContentFileInfo);
        }
    }

    /**
     * 修改知识/查无/纠错和文件的管理
     * @param fileIdList
     * @param klContentId
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAssociation(List<String> fileIdList, String klContentId) {
        List<String> deleteList = new ArrayList<>();
        KlContentFileInfo klContentFileInfo = new KlContentFileInfo();
        klContentFileInfo.setKlContentId(klContentId);
        klContentFileInfo.setKlFileIsDel("0");
        // 已经关联的文件
        List<KlContentFileInfo> fileInfoList = klContentFileInfoMapper.selectKlContentFileInfoList(klContentFileInfo);
        // 都是空，没有关联文件
        if (CollectionUtils.isEmpty(fileIdList) && CollectionUtils.isEmpty(fileInfoList)) {
            return;
        // 传递的是空，数据库有--表示全部删除
        }else if (CollectionUtils.isEmpty(fileIdList) && !CollectionUtils.isEmpty(fileInfoList)) {
            deleteList = fileInfoList.stream().map(KlContentFileInfo::getKlId).collect(Collectors.toList());
        // 传递的有数据，数据库是空--表示在修改的时候加了附件
        }else if (!CollectionUtils.isEmpty(fileIdList) && CollectionUtils.isEmpty(fileInfoList)) {
        // 传递的有数据，数据库也有数据， 要区分一下，有哪些是要删除的
        }else {
            for (KlContentFileInfo fileInfo : fileInfoList) {
                boolean isFile = true;
                for (String fileId : fileIdList) {
                    if (fileInfo.getKlId().equals(fileId)) {
                        isFile = false;
                        break;
                    }
                }
                if (isFile) {
                    deleteList.add(fileInfo.getKlId());
                }
            }
        }
        // 建立知识关联文件id
       if (!CollectionUtils.isEmpty(fileIdList)) {
           klContentFileInfo.setKlIds(fileIdList);
           klContentFileInfoMapper.updateKlContentFileInfoByIds(klContentFileInfo);
       }
       // 需要删除关联的文件
       if (!CollectionUtils.isEmpty(deleteList)) {
           KlContentFileInfo deleteFile = new KlContentFileInfo();
           deleteFile.setKlIds(deleteList);
           deleteFile.setKlFileIsDel("1");
           klContentFileInfoMapper.updateKlContentFileInfoByIds(deleteFile);
       }

    }


    /**
     * 导入文件，判断必填字段/字符串长度
     * */
    private String judgmentNotNull(KlContentInfoExcel excel, int lineNumber) {
        // 一级分类名称
        if (StringUtils.isBlank(excel.getOneSortName())) {
            return "第" + lineNumber + "行：一级分类名称-必填";
        }
        // 二级分类名称
        if (StringUtils.isBlank(excel.getTwoSortName())) {
            return "第" + lineNumber + "行：二级分类名称-必填";
        }
        // 知识形式
        if (StringUtils.isBlank(excel.getKlContentTypeName())) {
            return "第" + lineNumber + "行：知识形式-必填";
        }
        // 标题
        if (StringUtils.isBlank(excel.getKlContentTitle())) {
            return "第" + lineNumber + "行：标题-必填";
        }
        // 标题长度
        if (excel.getKlContentTitle().length() > 100) {
            return "第" + lineNumber + "行：标题-太长了";
        }
        // 知识内容
        if (StringUtils.isBlank(excel.getKlContent())) {
            return "第" + lineNumber + "行：知识内容-必填";
        }
        // 关键字
        if (StringUtils.isBlank(excel.getKlContentKeyword())) {
            return "第" + lineNumber + "行：关键字-必填";
        }
        // 关键字长度
        if (excel.getKlContentKeyword().length() > 50) {
            return "第" + lineNumber + "行：关键字-太长了";
        }
        // 知识来源
        if (StringUtils.isBlank(excel.getKlContentBelongUnit())) {
            return "第" + lineNumber + "行：知识来源-必填";
        }
        // 政策文号长度判断
        if (StringUtils.isNotBlank(excel.getPolicyNo())) {
            if (excel.getPolicyNo().length() > 50) {
                return "第" + lineNumber + "行：政策文号-太长了";
            }
        }
        // 相关工单编号长度判断
        if (StringUtils.isNotBlank(excel.getRelWpid())) {
            if (excel.getRelWpid().length() > 30) {
                return "第" + lineNumber + "行：相关工单编号-太长了";
            }
        }
        // 总条数长度判断
        if (StringUtils.isNotBlank(excel.getKlTotal())) {
            if (excel.getKlTotal().length() > 20) {
                return "第" + lineNumber + "行：总条数-太长了";
            }
        }
        return null;
    }

    /**
     * set 知识默认数据
     * */
    private void setDefaultKlContentInfo(KlContentInfo klContentInfo, LoginUser loginUser) {
        // 紧急程度0：一般；1：紧急
        klContentInfo.setKlContentLevel("0");
        // 6 待审核, 1 审核通过, -2 审核未通过, 2 删除待审核
        klContentInfo.setKlContentStatus("6");
        // 创建人
        klContentInfo.setKlContentCreater(loginUser.getUserId().toString());
        // 创建人姓名(真实姓名)
        klContentInfo.setKlContentCreaterName(loginUser.getUser().getNickName());
        // 来源:所属组织机构(部门id)
        klContentInfo.setKlContentSources(loginUser.getDeptId().toString());
        // 创建时间
        klContentInfo.setKlContentCreatetime(new Date());
        // 是否案例(1-是；0-不是)
        klContentInfo.setIsCase("0");
        // 是否上报给12345（0否，1是）
        klContentInfo.setKlContentIshotline("0");
        // 是否置顶（0否，1是）
        klContentInfo.setKlContentIstop("0");
        // 来源方式:1.界面录入2.数据接口3.webservice接口 4.导入文件
        klContentInfo.setKlContentSourcesType("4");
        // 操作类型 A 新增 M修改 D删除
        klContentInfo.setKlContentOpeType("A");
        // 是否删除 0 正常 1删除
        klContentInfo.setKlContentIsDel("0");
        // 核实时间--新增，该时间就是分布时间
        klContentInfo.setKlVerifyTime(klContentInfo.getKlContentPublishtime());
        if (StringUtils.isBlank(klContentInfo.getKlUpdateCycle())) {
            klContentInfo.setKlUpdateCycle("180");
        }
        int day = Integer.parseInt(klContentInfo.getKlUpdateCycle()) - 7;
        klContentInfo.setKlStartVerifyTime(DateUtils.plusDay(klContentInfo.getKlVerifyTime(),day));
        // 点击量
        klContentInfo.setKlContentHits(0L);
        // 评分
        klContentInfo.setKlContentScore(0.0);
    }

    /**
     * 新增知识/核实知识记录，由于统计用
     * @param klId 知识id
     * @param klSortId 知识分类id
     * @param klType 类型（1--新增知识，2--核实知识）
     * */
    @Transactional(rollbackFor = Exception.class)
    public void addKlContentVerifyLog(String klId, String klSortId, Integer klType) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        KlContentVerifyLog klContentVerifyLog = new KlContentVerifyLog();
        klContentVerifyLog.setKlId(klId);
        klContentVerifyLog.setKlSortId(klSortId);
        klContentVerifyLog.setKlType(klType);
        klContentVerifyLog.setCreateTime(new Date());
        klContentVerifyLog.setUserId(loginUser.getUserId());
        klContentVerifyLog.setRealName(loginUser.getUser().getNickName());
        klContentVerifyLog.setDeptId(loginUser.getDeptId());
        klContentVerifyLogMapper.insertKlContentVerifyLog(klContentVerifyLog);
    }


    /**
     * 清除知识内容中的html标签和属性
     * */
    @Override
    public String filterHtml(String contents) {
        String klContent = "";
        if (StringUtils.isNotBlank(contents)) {
            klContent = contents.replaceAll("\\&[a-zA-Z]{1,10};", "")
                    .replaceAll("<[^>]*>", "")
                    .replaceAll("[(/>)<]", "").trim();
        }
        return klContent;
    }


}
